package com.cac.demo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cac.demo.newCode.cemop.dto.CemopLogDTO;
import com.cac.demo.newCode.cemop.service.CemopService;
import com.cac.demo.util.adapter.ResponseMsg;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class AccessLogAspect {

    private final HttpServletRequest request;
    @Resource
    private  ObjectMapper objectMapper;
    @Resource
    CemopService cemopService;

    public AccessLogAspect(HttpServletRequest request) {
        this.request = request;
    }

    @AfterReturning(pointcut = "@annotation(AccessLog)", returning = "responseMsg")
    public void logAccess(JoinPoint joinPoint, ResponseMsg responseMsg){
        CemopLogDTO dto = new CemopLogDTO();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AccessLog accessLog = method.getAnnotation(AccessLog.class);
        try {
            // 获取方法参数
            String[] parameterNames = signature.getParameterNames(); // 获取参数名称
            Object[] parameterValues = joinPoint.getArgs();          // 获取参数值
            Map<String, Object> argsMap = new HashMap<>();
            //接收存接收的数据
            if ("receive".equals(accessLog.sendOrReceive())) {
                HashMap hashMap = (HashMap) responseMsg.getResponseBody();
                //获取 fileUrl
                String fileUrl = (String) hashMap.get("fileUrl");
                //获取xmlList
                String xmlList = objectMapper.writeValueAsString(hashMap.get("xmlList"));
                dto.setReceiveDataUrl(fileUrl);
                dto.setReceiveData(xmlList);
                dto.setSendDataUrl(" ");
                dto.setSendData(" ");
                //发送存发送的数据
            } else if ("send".equals(accessLog.sendOrReceive())) {
                JSONObject responseBodyJson = (JSONObject) responseMsg.getResponseBody();
                // 获取 BData
                JSONObject bDataJson = responseBodyJson.getJSONObject("BData");
                //获取 fileSendUrl
                String fileSendUrl = bDataJson.getString("fileSendUrl");
                System.out.println("fileSendUrl: " + fileSendUrl);
                String sendDataResult = objectMapper.writeValueAsString(responseBodyJson);
                dto.setSendData(sendDataResult);
                dto.setSendDataUrl(fileSendUrl);
                dto.setReceiveDataUrl(" ");
                dto.setReceiveData(" ");
            }else if ("sendTxt".equals(accessLog.sendOrReceive())) {
                JSONObject responseBodyJson = (JSONObject) responseMsg.getResponseBody();
                //获取 filePathUrl
                String fileSendUrl = responseBodyJson.getString("filePathUrl");
                String CemopUrl = responseBodyJson.getString("CemopUrl");
                String jsonArray = responseBodyJson.getString("jsonArray");
                dto.setSendData(jsonArray);
                dto.setSendDataUrl(fileSendUrl);
                dto.setReceiveDataUrl(CemopUrl);
                dto.setReceiveData(" ");
            }
            else if("receiveTxt".equals(accessLog.sendOrReceive())) {
                JSONObject responseBodyJson = (JSONObject) responseMsg.getResponseBody();
                //获取 fileUrl
                Object fileUrl = responseBodyJson.get("fileUrl");
                //获取内容
                ArrayList<Object> data = (ArrayList<Object>) responseBodyJson.get("data");
                JSONArray jsonArray = new JSONArray(data);
                dto.setReceiveDataUrl(fileUrl.toString());
                dto.setReceiveData(jsonArray.toString());
                dto.setSendDataUrl(" ");
                dto.setSendData(" ");
                //发送存发送的数据
            }else {
                String result = JSONObject.toJSONString(responseMsg.getResponseBody());
                String sendDataResult = JSONObject.toJSONString(parameterValues);
                Object responseBody = responseMsg.getResponseBody();
                dto.setSendData(sendDataResult);
                dto.setSendDataUrl("");
                dto.setReceiveDataUrl(" ");
                dto.setReceiveData(result);
            }
            dto.setLogType(accessLog.LogType());
            dto.setInterfaceName(request.getRequestURI());
            dto.setLogArea(request.getRemoteAddr());
            dto.setLogLevel(" ");
            dto.setLogPlatform(" ");
            cemopService.saveCemopLog(dto);
        } catch (Exception e) {
            // 记录异常信息
            log.error("Error logging access: ", e);
            dto.setLogType(accessLog.LogType());
            dto.setInterfaceName(request.getRequestURI());
            dto.setLogArea(request.getRemoteAddr());
            dto.setLogLevel(e.getMessage());
            dto.setLogPlatform(" ");
            cemopService.saveCemopLog(dto);

        }
    }
}
